<?php

namespace app\admin\command;

use app\admin\model\BuildingModel;
use app\admin\model\BuildingRoomModel;
use app\admin\model\HouseOwnerModel;
use app\admin\model\VacantModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Vacant extends Command
{

    protected function configure()
    {
        $this
            ->setName('make_vacant')
            ->setDescription('生成空置率');
    }

    protected function execute(Input $input, Output $output)
    {
        HouseOwnerModel::where(['status' => 1])->chunk(100, function ($rows) {
            foreach ($rows as $row) {
                $count = VacantModel::where('user_id', $row->user_id)
                    ->where('day', date('Y-m-d'))
                    ->count();
                if ($count > 0) {
                    continue;
                }
                $build_ids = BuildingModel::getUserBuildingIds($row->user_id);

                $total_num = BuildingRoomModel::whereIn('build_id', $build_ids)->count();

                if ($total_num > 0) {
                    $rent_num = BuildingRoomModel::whereIn('build_id', $build_ids)
                        ->where('status', 3)
                        ->count();
                    $k_num = $total_num - $rent_num;
                    $rate = bcdiv($k_num * 100, $total_num, 2);

                    VacantModel::create([
                        'user_id' => $row->user_id,
                        'total_num' => $total_num,
                        'rent_num' => $rent_num,
                        'rate' => $rate,
                        'year' => date('Y'),
                        'month' => date('Y-m'),
                        'day' => date('Y-m-d'),
                    ]);
                }

            }
        });

        $output->writeln('空置率生成完成');
    }


}
